<?php
namespace XWAM\Addon\PXCallSystem\Controller;
/**
 * 自动登录控制器
 *
 * @author Alen
 * @since 1.0 2014-6-19 by sutroon
 */
class AutoDutyController extends AppbaseController
{

    public function rule_list()
    {
        if (!$this->isSuperAdmin) {
            $where['siteID'] = $this->loginData['siteID'];
        }
        $list = sofunc_get_paging_list('tcti_auto_duty', $where, $show, array('ORDERBY' => 'siteID'));
        $this->assign('list', sofn_set_site_id_text($list));
        $this->assign('page', $show);
        $this->display2();
    }

    public function rule_edit()
    {
        $id = I('id');
        if ($id) {
            $M = M('tcti_auto_duty');
            $data = $M->find($id);
            if (!$data) {
                $this->ajaxMsg(false, '找不到记录!');
            }
            $this->assign('data', $data);
        } else {
            $this->assign('data', array('endTime' => '23:59:59'));
        }
        $this->display();
    }

    public function rule_save()
    {
        $dateType = I('dateType');
        $params = new \Org\Su\Params();
        $params->addParam('siteID', 'number', '租户未选择!');
        $params->addParam('extension', 'require', '分机名称必须填写!');
        $params->addParam('queue', 'require', '队列名称必须填写!');
        /*
        if ($dateType != '2') {
            $params->addParam('beginTime', 'require', '开始时间必须选择!');
            $params->addParam('endTime', 'require', '结束时间必须选择!');
        }
        $params->addParam('dateType', 'number', '日期类型必须选择!');
        */
        $params->addParam('state', 'number', '工作状态必须选择!');
        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }
        $params->addData('remark');
        $id = I('id');
        $hasId = strlen($id) > 0;
        $state = I('state');
        $oldstate = I('oldstate');
        $extension = I('extension');
        $queue = I('queue');
        $M = M('tcti_auto_duty');
        if ($id) {
            $where['id'] = $id;
            $result = $M->where($where)->save($params->getParams());
        } else {
            // 判断是否重复登录
            if ($M->where("siteID=" . $params->getParam('siteID') . " and extension='" . $extension . "' and queue='" . $queue . "'")->count() > 0) {
                $this->ajaxMsg(false, '分机 [' . $extension . '] 与队列 [' . $queue . '] 已添加过了!');
            }
            $params->addData('createdTime', date('Y-m-d H:i:s'));
            $result = $M->add($params->getParams());
            $id = $result;
        }

        if ($result === false) {
            $this->ajaxMsg(false, '保存失败!');
        } else {
            if ($state != $oldstate) {
                $result = $this->login_extension_static($queue, $extension, $state == '1' ? 'add' : 'del');
                if ($result['result']) {
                    $this->ajaxMsg(true, '操作成功', AddonU('AutoDuty/rule_list'));
                } else {
                    $this->ajaxMsg(false, '操作失败：' . $result['Message']);
                }
            }
            $this->ajaxMsg(true,'保存成功');
        }
    }

    // 登入静态分机
    function login_extension_static($queue, $extension, $opt = 'add')
    {
        $astman = create_asmanager();
        $queue = $queue;
        $interface = 'SIP/' . $extension;
        if ($opt == 'add') {
            $result = $astman->Command('queue add member SIP/' . $extension . ' to ' . $queue . ' penalty 0 as ' . $extension . ' state_interface SIP/' . $extension);
            $isSuccess = strpos($result['data'], 'Added interface') !== false;
        } else {
            $result = $astman->QueueRemove($queue, $interface); // 移除队列
            $isSuccess = $result['Response'] == 'Success';
        }
        return array('result' => $isSuccess, 'Message' => $result['Message']);
    }

    function login_extension_dynamic($state, $oldstate, $data, $hasId)
    {
        // 如果是新增用户则自动注册asterisk
        $M = M('tcti_auto_duty');
        if ($state == '1' && $state !== $oldstate) {
            $result = $this->save_asterisk($data, 'add');
        } else {
            $queue = $data['queue'];
            $extension = $data['extension'];
            $result = $M->execute("delete from asterisk.queues_details where id='$queue' and keyword='member' and data like 'Local/$extension@%'");
        }
        if ($result === false) {
            // 如果注册失败则删除已插入的记录
            $where['extension'] = $extension;
            $M->where($where)->delete();
            $this->ajaxMsg(false, '更新CTI基础服务失败!');
        } else {
            if ($hasId) {
                $this->ajax_cti_reload(AddonU('AutoDuty/rule_list', 'show=dialog'));
            } else {
                $msg = $this->save_to_additional($data, $state);
                if ($msg === true) {
                    $this->ajax_cti_reload(AddonU('AutoDuty/rule_list', 'show=dialog'));
                } else {
                    $this->ajaxMsg(false, '保存失败');
                }
            }
        }
    }

    function set_rule_state()
    {
        $state = I('val');
        $id = I('id');
        if (!$id) {
            $this->ajaxMsg(false, '编号无效!');
        }
        if ($state == '') {
            $this->ajaxMsg(false, '参数有误!');
        }
        $M = M('tcti_auto_duty');
        $where['id'] = $id;
        $stat = $M->where($where)->getField('enable');
        if ($stat === false) {
            $this->ajaxMsg(false, '项目不存在!');
        }
        if ($stat == $state) {
            $this->ajaxMsg(false, '重复操作!');
        }
        $result = $M->where($where)->setField('enable', $state);
        $this->ajaxMsg($result, '操作{%}!', array('', AddonU('AutoDuty/rule_list')));
    }

    /**
     * 保存到asterisk数据库
     * @param array $data
     * @param string $mode 模式,add=新增,update=更新
     * @since 1.0 2014-7-4 by sutroon
     */
    function save_asterisk($data, $mode)
    {
        $a = new \Think\Model\AdvModel();
        $result = $a->patchQuery($this->get_save_asterisk_sql($data, $mode));
        if ($result === false) {
            die('Error:' . $a->getDbError());
        }
        return $result;
    }

    protected function get_save_asterisk_sql($data, $mode = 'update')
    {
        if ($mode == 'update') {
            $arr[] = "update asterisk.queues_details set data='Local/" . $data['extension'] . "@from-queue/n,0' where id='" . $data['queue'] . "' and keyword='member';";
        } else {
            $n = M('asterisk.queues_details')->where("keyword='member'")->max('flags');
            if (!$n) {
                $n = 0;
            } else {
                $n = $n + 1;
            }
            $arr[] = "insert into asterisk.queues_details (id,keyword,data,flags) values ('" . $data['queue'] . "','member','Local/" . $data['extension'] . "@from-queue/n,0',$n);";
        }
        return $arr;
    }

    protected function save_to_additional($data, $activated = true)
    {
        if (!$data) {
            return '数据有误!';
        }
        if (!file_exists(queues_additional_path)) {
            return '配置文件不存在';
        }
        if (!is_writable(queues_additional_path)) {
            return '配置文件不允许读写';
        }

        $file_content = file_get_contents(queues_additional_path);
        if ($activated) {
            if (strstr($file_content, 'member=Local/' . $data['extension'] . '@')) {
                return '配置文件中已包含此分机号码';
            }
            $content = 'member=Local/' . $data['extension'] . '@from-queue/n,0,' . $data['extension'] . ',hint:' . $data['extension'] . '@ext-local';
            $fp = fopen(queues_additional_path, 'a+');
            fwrite($fp, $content);
            fclose($fp);
        } else {
            if (strstr($file_content, 'member=Local/' . $data['extension'] . '@')) {
                //$file_content = ereg_replace('member=Local/' . $data['extension'] . '@[^\[]*[^\[]?', "", $file_content);
                //file_put_contents(queues_additional_path, $file_content);
            }
        }
        return true;
    }

    /**
     * 删除项目
     */
    public function rule_delete()
    {
        $id = I('id');
        if (!$id)
            $this->ajaxMsg(false, '~编号丢失!');
        $M = M('tcti_auto_duty');
        $data = $M->find($id);
        if (!$data)
            $this->ajaxMsg(false, '~记录不存在!');
        $n = $data['extension'];
        if ($M->delete($id)) {
            // 删除alterisk表数据
            $M->execute("delete from asterisk.queues_details where id='" . $data['queue'] . "' and keyword='member' and data like 'Local/$n@%'");
            $msg = $this->save_to_additional($data, 0);
            if ($msg === true) {
                $this->ajax_cti_reload(AddonU('AutoDuty/rule_list', 'show=dialog'));
            } else {
                $this->ajaxMsg(false, '~' . $msg);
            }
        } else {
            $this->ajaxMsg(false, '~删除失败!');
        }
    }

}
